# -*- coding:utf-8 -*-

from flask import Flask, request, jsonify, abort
from flask_cors import CORS
from com.zzh.dao.puserDao import PuserDao

from . import app

CORS(app, supports_credentials=True)

'''个人用户表 zzh_puser API'''


@app.route('/puser-regist/<int:new_id>', methods=['POST'])
def puser_regist(new_id):
    if not request.json:
        abort(400)
    user_info = {
        "puser_name": request.json['puser_name'],
        "puser_job": request.json['puser_job'],
        "puser_address": request.json['puser_address'],
        "puser_idea": request.json.get('puser_idea', ''),
        "puser_code": request.json.get('puserCode', ''),
        "puser_province": request.json.get('puser_province', ''),
        "puser_city": request.json.get('puser_city', ''),
        "puser_town": request.json.get('puser_town', '')
    }
    result = PuserDao().add_puser_info(new_id, user_info)
    if result:
        return jsonify({"userInfo": user_info, "message": {"code": 1, "info": "添加成功！"}})
    else:
        return jsonify({"message": {"code": 0, "info": "添加失败！"}})


@app.route('/update-puser/<int:user_id>', methods=['POST'])
def update_puser(user_id):
    if not request.json:
        abort(400)

    oldInfo = PuserDao().query_puser_by_id(user_id)

    user_info = {
        "puser_name": request.json.get('puser_name', oldInfo[1]),
        "puser_job": request.json.get('puser_job', oldInfo[2]),
        "puser_address": request.json.get('puser_address', oldInfo[3]),
        "puser_email": request.json.get('puser_email', oldInfo[4]),
        "puser_idea": request.json.get('puser_idea', oldInfo[5]),
        "puser_img": request.json.get('puser_img', oldInfo[6]),
        "puser_code": request.json.get('puserCode', oldInfo[7]),
        "puser_province": request.json.get('puser_province', oldInfo[8]),
        "puser_city": request.json.get('puser_city', oldInfo[9]),
        "puser_town": request.json.get('puser_town', oldInfo[10])
    }
    result = PuserDao().update_puser(user_id, user_info)

    return jsonify({"userInfo": user_info, "message": {"code": 1, "info": "更新成功！"}})


@app.route('/query-puser/<int:user_id>', methods=['GET'])
def query_puser(user_id):
    query_result = PuserDao().query_puser_info(user_id)

    return jsonify({"userInfo": query_result, "message": {"code": 1, "info": "OK"}})
